import os

from flask import render_template, request, redirect, url_for, flash
from sqlalchemy import desc

from app import app, modles, db

# @app.before_request
from app.view.errors import CustomException


def before_request():
    # http 请求转发 https
    if request.url.startswith('http://'):
        url = request.url.replace('http://', 'https://', 1)
        code = 301
        return redirect(url, code=code)


@app.route('/')
@app.route('/hot', endpoint='hot_index')
def index():
    path = request.path
    hot = True if path == '/hot' else False

    sort_id = request.args.get("sort")
    page = request.args.get("page", 1, int)
    limit = 10

    filter_by = {'is_delete': 0}
    order_by = {}
    if sort_id:
        filter_by['sort_id'] = sort_id
    if hot:
        order_by = {desc(modles.Website.order)}

    sort = modles.WebsiteSort.query.filter_by(is_delete=0, id=sort_id).first()
    sites = modles.Website.query.filter_by(**filter_by).order_by(*order_by).paginate(page, limit)

    return render_template('index.html', sites=sites, sort=sort)


@app.route('/test')
def testapp():
    if (1 < 0):
        raise CustomException(410, 'GitHub 无反应')

    return {'msg': app.config['SQLALCHEMY_DATABASE_URI']}
